package org.nutz.j2cache.spring;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.J2Cache;

public class SpringJ2CacheManager implements CacheManager {
	
	protected CacheChannel channel;
	
	protected Map<String, Cache> caches;
	
	protected Object lock;
	
	public SpringJ2CacheManager() {
		channel = J2Cache.getChannel();
		caches = new ConcurrentHashMap<String, Cache>();
		lock = new Object();
	}

	public Cache getCache(String name) {
		Cache cache = caches.get(name);
		if (cache == null) {
			synchronized (lock) {
				cache = caches.get(name);
				if (cache == null) {
					cache = new SpringJ2Cache(name, channel);
					caches.put(name, cache);
				}
			}
		}
		return cache;
	}

	public Collection<String> getCacheNames() {
		return Collections.unmodifiableCollection(caches.keySet());
	}

}
